import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../services/error_logger_service.dart';
import '../../shared/widgets/error_widget.dart';

class GlobalErrorHandler {
  static void setup() {
    // 捕获 Flutter 框架错误
    FlutterError.onError = (FlutterErrorDetails details) {
      // 忽略键盘事件相关的警告（模拟器中的已知问题，不影响功能）
      if (details.exception.toString().contains('KeyUpEvent') ||
          details.exception.toString().contains('HardwareKeyboard') ||
          details.exception.toString().contains('Caps Lock')) {
        // 这是 Flutter 框架的已知问题，不影响功能，可以忽略
        return;
      }
      
      if (kDebugMode) {
        FlutterError.presentError(details);
      }
      
      ErrorLoggerService.logError(
        details.exception,
        stackTrace: details.stack,
        context: 'Flutter Framework',
      );
    };

    // 捕获异步错误（Zone）
    ErrorWidget.builder = (FlutterErrorDetails details) {
      if (kDebugMode) {
        return ErrorWidget(details.exception);
      }
      
      return Material(
        child: AppErrorWidget(
          error: details.exception,
          title: '应用错误',
        ),
      );
    };
  }

  /// 处理未捕获的异步错误
  static void handleAsyncError(Object error, StackTrace stack) {
    ErrorLoggerService.logError(
      error,
      stackTrace: stack,
      context: 'Async Error',
    );
  }
}

